package com.javastudy.thread;

import java.util.concurrent.locks.LockSupport;

public class ParkUnparkTest {

    public static Object baozi = null;

    public static void main(String[] args) throws InterruptedException {
        ParkUnparkTest test = new ParkUnparkTest();
//        test.ParkUnparkTest();//正常情况
//        test.ParkUnparkTest2();//令牌许可机制，不对顺序有要求

        test.ParkUnparkDeadLockTest();//死锁状态



    }

    public void ParkUnparkTest() throws InterruptedException {
        Thread consumer = new Thread(() -> {
            System.out.println("1.出来买包子");
            while(baozi == null){
                System.out.println("2.没有包子，进入等待");
                LockSupport.park();
            }
            System.out.println("3.买到包子，回家");
        });
        consumer.start();
        Thread.sleep(3000);
        baozi = new Object();//3秒后生产出一个包子
        System.out.println("4.生产出包子了，通知消费者");
        LockSupport.unpark(consumer);
    }

    public void ParkUnparkTest2() throws InterruptedException {
        Thread consumer = new Thread(() -> {
            System.out.println("1.出来买包子");
            while(baozi == null){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("2.没有包子，进入等待");
                LockSupport.park();
            }
            System.out.println("3.买到包子，还想买一个");
            baozi = null;
            LockSupport.park();
        });
        consumer.start();
        Thread.sleep(3000);
        baozi = new Object();//3秒后生产出一个包子
        System.out.println("4.生产出包子了，通知消费者");
        LockSupport.unpark(consumer);
    }

    public void ParkUnparkDeadLockTest() throws InterruptedException {
        Integer a = 3;
        Thread consumer = new Thread(() -> {
            System.out.println("1.出来买包子");
            while(baozi == null){
                synchronized(a){
                    System.out.println("2.没有包子，进入等待");
                    LockSupport.park();
                }
            }
            System.out.println("3.买到包子，还想买一个");
            baozi = null;
            LockSupport.park();
        });
        consumer.start();
        Thread.sleep(3000);
        baozi = new Object();//3秒后生产出一个包子
        System.out.println("4.生产出包子了，通知消费者");
        synchronized (a){
            LockSupport.unpark(consumer);
        }
    }
}
